<template>
  <div class="content">
    <el-form :inline="true" :model="serchForm" class="demo-form-inline">
      <el-form-item label="内容">
        <el-input v-model="serchForm.name" placeholder="设备名称、备注" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="serchForm.status" clearable placeholder="状态" style="width:120px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="onSubmit" circle ><el-icon><Search /></el-icon></el-button>
        
          <el-button type="success" @click="onLoding"  >刷新</el-button>
       
          <el-button  @click="handleClickAdd(null,null)" type="primary" plain ><el-icon><Plus /></el-icon>添加</el-button >
      </el-form-item>
    </el-form>
    <el-table row-key="id" empty-text="暂无数据" v-loading="loading" default-expand-all :data="tableData"
    @sort-change="sortChange"  style="width: 100%;height: calc(100vh - 142px);" border>

      <el-table-column fixed type="index" label="序号" align="center" min-width="55"></el-table-column>
      <el-table-column prop="name" fixed label="名称" sortable="custom"   show-overflow-tooltip min-width="200" />
      <el-table-column prop="code" label="类型编号" show-overflow-tooltip min-width="200"  />
      <el-table-column prop="type" label="类型" show-overflow-tooltip min-width="200" >
        <template #default="scope">
            
            <el-tag size="small" type="success" v-if="scope.row.type === 1">设备</el-tag>
            <el-tag size="small" type="primary" v-if="scope.row.type === 2">类型</el-tag>

        </template>
      </el-table-column>

      <el-table-column prop="content" label="备注" show-overflow-tooltip min-width="120"  />
      <el-table-column label="状态" min-width="120" prop="status"  sortable="custom"  align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @change="onStatus(scope.row.id)" >
            <template #active-action>
              <span class="custom-active-action">启</span>
            </template>
            <template #inactive-action>
              <span class="custom-inactive-action">禁</span>
            </template>
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" sortable="custom" label="添加时间" show-overflow-tooltip width="180"  />

      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" link class="button-edit" 
            size="small" @click="handleClickInfo(scope.row.id)">
            查看
          </el-button>
          <el-button type="success" link class="button-edit" 
            size="small" @click="handleClickEdit(scope.row.id)">
            修改
          </el-button>
          <!-- <el-button type="danger" link class="button-delete" v-if="route.meta.roles.includes('company:delete')"
            size="small" @click="handleClickDelete(scope.row.id)">删除</el-button> -->

            <el-popconfirm
              width="220"
              icon-color="#626AEF"
              title="确认删除该数据?"
              @confirm="onConfirm(scope.row.id)"
              
            >
              <template #reference>
                <el-button size="small" :disabled="scope.row.children.length>0?true:false" :type="scope.row.children.length > 0?'info':'danger'" link >删除</el-button>
              </template>

              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">否</el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="confirm"
                >
                  是
                </el-button>
              </template>
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog v-model="formDialog.show" :title="formDialog.title"  width="80%" align-center draggable>
      <formView  v-if="formDialog.show" :pid="formDialog.pid" :type="formDialog.type" :id="formDialog.id" @close-dialog="closeDialog"/>
    </el-dialog>

  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import { equipApi } from '@/utils/api/equip';
import { ElMessage } from 'element-plus'
import formView from './create.vue'
const route = useRoute();
console.log(route, '000'); // 输出当前路由的路径
const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
const statusOptions = proxy.$statusOptions; // 访问全局状态。注意：这种方式依赖于全局属性的直接访问，这在Vue官方文档中是不推荐的。更好的实践是使用provide/inject或状态管理库。
interface Tree {
  label: string
  children?: Tree[]
}

const sortChange = ({ column, prop, order }) => {
  serchForm.sortBy = {};
  // 处理排序逻辑
  if (order === 'ascending') {
    order = 'asc'
    // getList();
  } else if (order === 'descending') {
    order = 'desc'
  } else {
    // 重置排序或进行其他操作
  }
  Object.assign(serchForm.sortBy, {[prop]:order});
  getList();
      
}

//状态修改
const onStatus = async (id: number) => {
  
  await equipApi.status({id:id})
  getList() 
}

const loading = ref(false)
const tableData = ref([])

const convertToTree = (data: any[]): Tree[] => {
  const tree = [];
  const map = {};

  // 第一步：创建一个以 id 为键的映射表
  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // 第二步：找出所有可能的父节点 id
  const allParentIds = new Set(data.map(item => item.pid));

  // 第三步：构建树形结构
  data.forEach(item => {
    if (!map[item.pid]) {
      // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
      tree.push(map[item.id]);
    } else {
      // 否则，找到其父节点并将其添加到父节点的 children 数组中
      const parent = map[item.pid];
      if (parent) {
        parent.children.push(map[item.id]);
      }
    }
  });

  return tree;
}

const serchForm = reactive({
  name: '',
  status: null,
  page: 1,
  limit: 10,
  sortBy:{}
})

const onSubmit = () => {
  console.log('submit!')
  serchForm.page = 1
  
  getList()
}
const onLoding = () => {
  loading.value = true

  serchForm.page = 1
  serchForm.limit = 10
  serchForm.name = ''
  serchForm.status = null
  serchForm.sortBy = {}
  getList()
}
const formDialog = reactive(  {
  show: false,
  title: '添加',
  id: null,
  type: 'add'
})
const handleClickAdd = (id,pid) => {
  formDialog.show = true
  formDialog.id = id
  formDialog.pid = pid
  formDialog.type = 'add'
  formDialog.title = '添加'

  // router.push({ name: 'companyCreate', params: { id: 0 } })
}

const handleClickInfo = (id: number) => {
  // router.push({ name: 'companyInfo', params: { id: id } })
  formDialog.show = true
  formDialog.title = '详情'
  formDialog.id = id
  formDialog.type = 'info'
}

const handleClickEdit = (id: number) => {
  formDialog.show = true
  formDialog.title = '修改'
  formDialog.id = id
  formDialog.type = 'edit'
  // router.push({ name: 'companyCreate', params: { id: id } })
}

const onConfirm = async (id: number) => {
  await equipApi.delete({id:id})
  getList() 
}


const getList = async () => {
  try {
    loading.value = true
    const res = await equipApi.getlist(serchForm)
    console.log(res,'009')
    if(res.code === 200){
      loading.value = false
      res.data.forEach((item:any) => {
        item.status = item.status === 1 ? true : false
      })
      tableData.value = convertToTree(res.data)
    }else{
      tableData.value  = []
      ElMessage({
        type: res.type,
        message: res.message,
      })
      loading.value = false
    }
  } catch (error) {
    console.log(error);
  }

}
onMounted(() => {
  getList()

})
const closeDialog = () => {
  formDialog.show = false
  getList()
}
</script>

<style scoped>
.demo-form-inline {
  padding-bottom: 0;
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
</style>
